<?php
namespace app\controllers;
use app\common\corelib\CacheHelper;
use app\common\HttpCurl;
use app\common\PayMethodEnum;
use app\common\PayUtil;
use app\logic\OrderLogic;
use Yii;




class OrderController extends BaseController
{
    const LIMIT = 10;
	public function actionIndex()
	{
            echo "index";
	}

    public function actionNotify(){
	    $request = Yii::$app->request->post();
        file_put_contents(date("Ymd").".txt", json_encode($request)." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);

        //$request = '{"returnUrl":"http:\/\/163.youoil.cn:8088\/#\/success?order_no=2019042898485249","payResultDesc":"\u652f\u4ed8\u6210\u529f","paygatewayOrderNo":"20190420174135004675","extend1":"http:\/\/163.youoil.cn:8088\/#\/success?order_no","signType":"1","thirdPartyCode":"eCardNewPay","signContent":"RGf7e5Bfio08aO4nRvN5aZiaI8BjowWbfLclH9fusSw2zenC6w2VXQZcX2mrnQyQZF5j9EYk7N8I5L0AZNTLaQ36ZfXaBcEf\/yGuWTMrlOUFfmK+tpIWLPCGp7Tl0JfbZnUhHLf9Mr2GJdZ2Kc9Dv9s0E8vXG\/+LYxT+hqBQbtA=","charset":"UTF-8","extend2":"{productName:\'95%\u9e45\u7ed2\u513f\u7ae5\u6625\u6b3e\u900f\u6c14\u7fbd\u7ed2\u88ab \u53ef\u505a\u5b50\u6bcd\u88ab\',cardType:\'P\',merchantName:\'\u4e2d\u7ecf\u7535\u5546\',mid:\'0101012014\',tid:\'4401A752\',acqId:\'\',shopCode:\'44015159\'}","orderTime":"20190420174135","payTime":"20190420174240","password":"","version":"v2.0","currency":"CNY","amount":"699","accountName":"wangyiyanxuanshangcheng","orderNo":"2019042898485249","partnerCode":"C000255","payResultCode":"S","notifyUrl":"http:\/\/163.youoil.cn:8188\/order\/notify"}';
        //$request = json_decode($request,true);
        $payResult = $request['payResultCode'];
        $order_no = $request['orderNo'];
        $pay_time = $request['payTime'];
        $pay_no = $request['paygatewayOrderNo'];
        $thirdPartyCode = $request['thirdPartyCode'];
        $signContentR = $request['signContent'];
        $orderLogic = new OrderLogic();
        if($payResult=='S'){
            $pu = new PayUtil();
            $signContent = $pu->verify($request);
            if(true || $signContent==$signContentR){
                $result = $orderLogic->paySuccess($order_no,$pay_time,$pay_no,$thirdPartyCode,$order_id);
                /*if($result){
                    foreach ($result['orderPackages'] AS $key=>$value){
                        $orderLogic->addPackage($order_id,$value);
                    }
                }*/
                echo '<?xml version=\"1.0\" encoding=\"UTF-8\"?><result>1</result>';exit;
            }else{
                return false;
            }
        }
    }

    public function actionPay(){
        $order_no = $this->getQueryparams('order_no','');
        $orderLogic = new OrderLogic();
        $url = $orderLogic->pay($order_no);
        $this->response(['pay_url'=>$url]);
    }

    public function actionMyOrder(){
        $order_status = $this->getQueryparams('order_status',-1);
        $page = $this->getQueryparams('page',1);
        $return = $this->getQueryparams('return',0);
        $orderLogic = new OrderLogic();
        $orders = $orderLogic->getOrderList($this->user_id,$page,self::LIMIT,$order_status,$return);
        $order_ids = array_column($orders,'order_id');
        $orderSkus = $orderLogic->getOrderSkus($order_ids);
        $orderSkusCount = $orderLogic->getOrderSkusCount($order_ids);
        $total_num = [];
        foreach ($orderSkusCount AS $key=>$value){
            $total_num[$value['order_id']] = $value['total_num'];
        }
        $packages = [];
        foreach($orderSkus AS $ke=>$va){
            $va['sku_pic'] = Yii::$app->params['pic_domain'].$va['sku_pic'];
            $va['sku_spec'] = json_decode($va['sku_spec'],true);
            if($va['package_id']){
                $packages[$va['order_id']][$va['package_id']]['package_id'] = $va['package_id'];
                $packages[$va['order_id']][$va['package_id']]['package_status'] = $va['package_status'];
                $packages[$va['order_id']][$va['package_id']]['is_show'] = 1;
                    $packages[$va['order_id']][$va['package_id']]['skus'][] = $va;
            }else{
                $packages[$va['order_id']][0]['package_status'] = 1;
                if($va['order_status']==2)
                    $packages[$va['order_id']][0]['package_status'] = 3;
                $packages[$va['order_id']][0]['package_id'] = 0;
                $packages[$va['order_id']][0]['is_show'] = 0;
                    $packages[$va['order_id']][0]['skus'][] = $va;
            }
        }
        foreach ($packages as &$package) {
            $package = array_values($package);
        }
        foreach ($orders AS $k=>&$v){
            $v['total_num'] = $total_num[$v['order_id']];
            $v['packages'] = $packages[$v['order_id']];
        }
        $this->response($orders);
    }

    public function actionCancelOrder(){
        $order_no = $this->getQueryparams('order_no','');
        $orderLogic = new OrderLogic();
        $result = $orderLogic->cancelOrder($order_no,$rejectReason);
        if($result){
            $this->response();
        }else{
            $this->error('60004',$rejectReason);
        }

    }

    public function actionConfirmReceipt(){
        $package_id = $this->getQueryparams('package_id',0);
        $orderLogic = new OrderLogic();
        $orderLogic->confirmPackage($package_id);
        $this->response();
    }

    public function actionOrderDetail(){
        $order_no = $this->getQueryparams('order_no','');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderDetail($order_no);
        $orderSkus = $orderLogic->getOrderSkus($order['order_id']);
        $orderSkusCount = $orderLogic->getOrderSkusCount($order['order_id']);
        $order['total_num'] = $orderSkusCount[0]['total_num'];
        foreach($orderSkus AS $ke=>$va){
            $va['sku_pic'] = Yii::$app->params['pic_domain'].$va['sku_pic'];
            $va['sku_spec'] = json_decode($va['sku_spec'],true);
            if($va['package_id']){
                $packages[$va['package_id']]['package_id'] = $va['package_id'];
                $packages[$va['package_id']]['package_status'] = $va['package_status'];
                $packages[$va['package_id']]['is_show'] = 1;
                $packages[$va['package_id']]['skus'][] = $va;
            }else{
                $packages[0]['package_status'] = 1;
                if($va['order_status']==2)
                    $packages[0]['package_status'] = 3;
                $packages[0]['package_id'] = 0;
                $packages[0]['is_show'] = 0;
                $packages[0]['skus'][] = $va;
            }
        }
        $packages = array_values($packages);
        $order['packages'] = $packages;
        switch($order['pay_type']){
            case "wxGzhPay":
                $order['pay_type'] = "微信支付";
                break;
            case "alipayWapPay":
                $order['pay_type'] = "支付宝";
                break;
            case "wxH5Pay":
                $order['pay_type'] = "微信支付(H5)";
                break;
            case "UnionpayParty":
                $order['pay_type'] = "银联在线";
                break;
        }
        $this->response($order);
    }

    public function actionShipping(){
        $package_id = $this->getQueryparams('package_id',0);
        $orderLogic = new OrderLogic();
        $express = $orderLogic->getExpress($package_id);
        $result = [];
        foreach ($express AS $key=>$value){
            $temp = HttpCurl::post("yanxuan.order.express.get",['orderId'=>$value['order_no'],'packageId'=>$value['yx_package_id'],'expressNo'=>$value['express_no'],'expressCom'=>$value['express_company']]);
            $temp = json_decode($temp,true);
            $result[$key]['express_company'] = $value['express_company'];
            $result[$key]['express_no'] = $value['express_no'];
            if(isset($temp['content']))
                $result[$key]['content'] = $temp['content'];
            else
                $result[$key]['content'] = [];
        }
        $this->response($result);
    }

    public function actionReturnSku(){
        $package_id = $this->getQueryparams('package_id',0);
        $orderLogic = new OrderLogic();
        $orderSkus = $orderLogic->getOrderSkusByPackage($package_id);
        $sku_ids = array_column($orderSkus,'sku_id');
        $yetOrderSkus = $orderLogic->getYetOrderSkusByPackage($package_id,$sku_ids);
        $fin_num = [];
        foreach($yetOrderSkus AS $key=>$value){
            $fin_num[$value['sku_id']] = $value['sku_num'];
        }
        foreach($orderSkus AS $k=>&$v){
            $v['sku_pic'] = Yii::$app->params['pic_domain'].$v['sku_pic'];
            $v['sku_spec'] = json_decode($v['sku_spec'],true);
            if(isset($fin_num[$v['sku_id']])){
                $v['num'] = $v['num'] - $fin_num[$v['sku_id']];
            }
            if($v['num']==0){
                unset($orderSkus[$k]);
            }
        }
        $this->response($orderSkus);
    }

    public function actionReturn(){
        $package_id = $this->getQueryparams('package_id',0);
        $sku_id = $this->getQueryparams('sku_id',0);
        $num = $this->getQueryparams('num',1);
        $reason_type = $this->getQueryparams('reason_type',0);
        $reason_detail = $this->getQueryparams('reason_detail','');
        $service_pics = $this->getQueryparams('service_pics','');
        $customer_name = $this->getQueryparams('customer_name','');
        $customer_phone = $this->getQueryparams('customer_phone','');
        $orderLogic = new OrderLogic();
        $result = $orderLogic->returns($this->user_id,$package_id,$sku_id,$num,$reason_type,$reason_detail,$service_pics,$customer_name,$customer_phone);
        if($result)
            $this->response(['service_no'=>$result]);
        else
            $this->error('60006','当前商品正常退货中，请选择其他商品退货');
    }

    public function actionCancelService(){
        $service_no = $this->getQueryparams('service_no','');
        $orderLogic = new OrderLogic();
        $orderLogic->cancelReturns($this->user_id,$service_no);
        $this->response();
    }

    public function actionServiceExpress(){
        $service_no = $this->getQueryparams('service_no','');
        $express_company = $this->getQueryparams('express_company','');
        $express_no = $this->getQueryparams('express_no','');
        $orderLogic = new OrderLogic();
        $orderLogic->serviceExpress($this->user_id,$service_no,$express_company,$express_no);
        $this->response();
    }

    public function actionServiceList(){
        $orderLogic = new OrderLogic();
        $service = $orderLogic->serviceList($this->user_id);
        foreach ($service AS $key=>&$value){
            $value['sku_pic'] = Yii::$app->params['pic_domain'].$value['sku_pic'];
            $value['sku_spec'] = json_decode($value['sku_spec'],true);
            if($value['yanxuan_status'] == 1){
                $value['service_status'] = 0;
            }elseif($value['yanxuan_status']==2){
                $value['service_status'] = 1;
            }elseif($value['yanxuan_status']==3){
                $value['service_status'] = 2;
            }elseif($value['yanxuan_status']==9){
                $value['service_status'] = 3;
            }elseif($value['yanxuan_status']==4){
                $value['service_status'] = 4;
            }elseif($value['yanxuan_status']==5){
                $value['service_status'] = 5;
            }elseif($value['yanxuan_status']==6){
                $value['service_status'] = 6;
            }
        }
        $this->response($service);
    }

    public function actionServiceDetail(){
        $service_no = $this->getQueryparams('service_no','');
        $orderLogic = new OrderLogic();
        $service = $orderLogic->serviceDetail($this->user_id,$service_no);
        $this->response($service);
    }

    public function actionYanxuanOrderGet(){
        $order_no = $this->getQueryparams('order_no','');
        print_r(HttpCurl::post("yanxuan.order.paid.get",['orderId'=>$order_no]));
    }

    public function actionRefundDetailGet(){
        $yx_service_id = $this->getQueryparams('yx_service_id','');
        print_r(HttpCurl::post("yanxuan.order.refund.detail.get",['applyId'=>$yx_service_id]));
    }

}
